#include "esp_log.h"
#include "esp_netif.h"
#include "esp_sntp.h"
#include "esp_timer.h"
#include "esp_wifi.h"
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <sys/time.h>

#define WIFI_SSID "iKuai2G-cc7b"
#define WIFI_PASS "314314314"

static const char *TAG = "wifi";

// ✅ 连接 WiFi
void wifi_init() {
  ESP_LOGW(TAG, "初始化...");
  esp_netif_init();
  esp_netif_create_default_wifi_sta();

  wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  esp_wifi_init(&cfg);

  wifi_config_t wifi_config = {};
  snprintf((char *)wifi_config.sta.ssid, sizeof(wifi_config.sta.ssid),
           WIFI_SSID);
  snprintf((char *)wifi_config.sta.password, sizeof(wifi_config.sta.password),
           WIFI_PASS);

  esp_wifi_set_mode(WIFI_MODE_STA);
  esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
  esp_wifi_start();
  esp_wifi_connect();
}

// ✅ 等待 SNTP 同步完成
void obtain_time() {
  ESP_LOGW(TAG, "初始化 SNTP...");
  esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);
  esp_sntp_setservername(0, "ntp.aliyun.com");
  esp_sntp_init();

  // 等待时间同步
  time_t now = 0;
  struct tm timeinfo = {};
  int retry = 0;
  const int retry_count = 10;
  while (timeinfo.tm_year < (2023 - 1900) && ++retry < retry_count) {
    ESP_LOGI(TAG, "等待时间同步... (%d/%d)", retry, retry_count);
    vTaskDelay(pdMS_TO_TICKS(2000));
    time(&now);
    localtime_r(&now, &timeinfo);
  }

  if (timeinfo.tm_year >= (2023 - 1900)) {
    ESP_LOGI(TAG, "时间已同步成功");
  } else {
    ESP_LOGW(TAG, "时间同步失败");
  }
}

void print_time() {
  time_t now;
  time(&now);

  struct tm timeinfo;
  localtime_r(&now, &timeinfo);

  char buf[64];
  strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
  printf("Current time: %s\n", buf);
}

void wifi_task(QueueHandle_t gpio_evt_queue) {
  int evt;
  while (1) {
    if (xQueueReceive(gpio_evt_queue, &evt, portMAX_DELAY)) {
        printf("GPIO pressed, doing Wi-Fi stuff...\n");

        /* wifi_init();
        obtain_time(); */
    }
  }
}